#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re
import xml.dom.minidom
import resolve_svd_mo as svd_inf

table_head_str = ''' 
	\\begin{center}
		\\tablefirsthead{   \hline
		\\textbf{Bits} & \\textbf{Name} & \\textbf{Access} & \\textbf{Decription} \\\\ \chline
			\hline}
		\\tablehead{   \hline
		\\textbf{Bits} & \\textbf{Name} & \\textbf{Access} & \\textbf{Decription} \\\\ \chline
		\hline}
		\\tabletail{%
    	\hline}
		\def\\arraystretch{1.5}
		\\begin{xtabular}{|c|c|c|p{11cm}|}
'''
# \\begin{xtabular}{|p{1cm}|p{2cm}|p{1.2cm}|p{10cm}|}
#		\\begin{xtabular}{|c|c|c|p{12cm}|}

table_end_str = '''
		\end{xtabular}
	\end{center}

'''

def line_str_pre(field_desp_str):
    str1 = re.sub(r'\n', '\\\\newline ', field_desp_str.strip())
    str2 = re.sub(r'\n[ |\t]+', ' ', str1)
    str3 = re.sub(r'_', '\_', str2)
    return str3

def field_table(reg_desp_dict = {}, addr = ""):
    file_str = ""

    for key in  reg_desp_dict:
        reg_addr = str(hex(int(reg_desp_dict[key][1][0:7], 16) + int(addr, 16))).upper().replace('X', 'x')
        reg_str = "\subsubsection{" + line_str_pre(reg_desp_dict[key][0]) + "}\n" + "Address: " + reg_addr + ". Reset: " + reg_desp_dict[key][2] +  "\n\\newline \n" + reg_desp_dict[key][3]
        field_tuple = reg_desp_dict[key][5]
        field_str = ""
        for item in field_tuple:
            # bits， name， access， description
            field_str += "        " + item[1][1] + " & "+ line_str_pre(item[1][2]) + " & "+ item[1][3] + " & "+ line_str_pre(item[1][4]) + "\\\\ \\hline\n"
 
        file_str += reg_str + table_head_str + field_str.strip('\n') + table_end_str
    
    return file_str


def gen_all_peri_reg(svd_name):
    DOMTree = xml.dom.minidom.parse(svd_name)
    collection = DOMTree.documentElement
    file_str = ""

    # 在集合中获取所有外设
    peripherals = collection.getElementsByTagName("peripheral")
    reg_info_dict = []

    for peri in  peripherals:
        name = peri.getElementsByTagName('name')[0].childNodes[0].data
        addr = peri.getElementsByTagName('baseAddress')[0].childNodes[0].data
        file_str += name + " address start \\newline\n"
        if peri.getElementsByTagName('register').length != 0:
            peri.getElementsByTagName("register")[0].childNodes[0].data
            reg_info_dict = svd_inf.get_peri_regs_info(peri.getElementsByTagName('register'))
        else:
            print("inherit: " + peri.getElementsByTagName("name")[0].childNodes[0].data)

        
        file_str += field_table(reg_info_dict, addr)
        file_str += name + " address end \\newline\n"
    return file_str


def gen_reg_latex(svd_name, latex_name):
    fi = open(latex_name, 'w')
    fi.write(gen_all_peri_reg(svd_name))
    fi.close()
